#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <unistd.h>
class TicketSystem
{
public:
    TicketSystem(int total) : tickets(total) {}

    void sellTicket()
    {

        while (true)
        {
            pthread_mutex_lock(&mutex); // 加锁 阻塞其他线程
            if (tickets > 0)
            {
                // 模拟处理时间
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                tickets--;
                std::cout << "售出1张票，剩余: " << tickets
                          << " (线程ID: " << std::this_thread::get_id() << ")\n";
                pthread_mutex_unlock(&mutex); // 解锁
                usleep(10);//稍做等待防止单一线程独占锁
            }
            else
            {
                pthread_mutex_unlock(&mutex); // 解锁
                break;
            }
        }
    }
    int getRemaining()
    {
        return tickets;
    }

private:
    int tickets;
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 通过宏 PTHREAD_MUTEX_INITIALIZER 快速初始化一个默认属性的互斥锁
};

int main()
{
    const int TOTAL_TICKETS = 100;
    const int THREAD_NUM = 10;

    TicketSystem system(TOTAL_TICKETS);
    std::vector<std::thread> threads;

    for (int i = 0; i < THREAD_NUM; ++i)
    {
        threads.emplace_back([&system]()
                             { system.sellTicket(); });
        
    }

    for (auto &t : threads)
    {
        t.join();
    }

    std::cout << "最终剩余票数: " << system.getRemaining() << std::endl;
    return 0;
}